package com.wus.system.service.impl;

import cn.hutool.crypto.digest.BCrypt;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wus.common.core.domain.user.AccountInfo;
import com.wus.common.core.exception.BusinessException;
import com.wus.common.mybatis.core.util.PageUtil;
import com.wus.system.entity.SysUser;
import com.wus.system.mapper.SysUserMapper;
import com.wus.system.request.LoginUserReq;
import com.wus.system.request.PageRequest;
import com.wus.system.request.SysUserRegisterReq;
import com.wus.system.request.SysUserPageReq;
import com.wus.common.core.domain.page.PageResultDTO;
import com.wus.system.service.ISysUserService;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 用户信息表 服务实现类
 * </p>
 *
 * @author wus
 * @since 2024-12-31
 */
@RequiredArgsConstructor
@Service
public class SysUserServiceImpl implements ISysUserService {

    private final Logger logger = LoggerFactory.getLogger(SysUserServiceImpl.class);

    private final SysUserMapper baseMapper;

    @Override
    public AccountInfo login(LoginUserReq req) {
        SysUser sysUser = baseMapper.selectOne(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getUserName, req.getUsername()));
        if (sysUser == null) {
            throw BusinessException.newInstance("用户名不存在！");
        }
        if (!BCrypt.checkpw(req.getPassword(), sysUser.getPassword())) {
            throw BusinessException.newInstance("密码错误！");
        }
        logger.info("登录成功，req：{}", req);
        AccountInfo accountInfo = new AccountInfo();
        accountInfo.setUserId(sysUser.getId());
        accountInfo.setUserName(sysUser.getUserName());
        accountInfo.setNickName(sysUser.getNickName());
        accountInfo.setDeptId(sysUser.getDeptId());
        return accountInfo;
    }

    @Override
    public Boolean register(SysUserRegisterReq req) {
        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(req, sysUser);
        // 明文转密文
        sysUser.setPassword(BCrypt.hashpw(req.getPassword()));
        return baseMapper.insert(sysUser) > 0;
    }

    @Override
    public PageResultDTO page(PageRequest req) {
        Page<SysUser> page = baseMapper.selectPage(new Page<>(req.getPageNum(), req.getPageSize()), Wrappers.emptyWrapper());
        // 不需要转换记录实体时，入参转换函数传null即可
        return PageUtil.transformEntityAndReturn(page, null);
    }

    @Override
    public PageResultDTO customPage(SysUserPageReq req) {
        Page<SysUser> page = baseMapper.findCustomPage(new Page<>(req.getPageNum(), req.getPageSize()), req.getKeyword());
        // 不需要转换记录实体时，入参转换函数传null即可
        return PageUtil.transformEntityAndReturn(page, null);
    }
}
